"ui";
var storage = storages.create("CM");
var tk = storage.get('tk')
if(tk == undefined){
    tk = {}
    storage.put('tk', tk)
}


ui.layout(
    <vertical padding="16">
        <button id="do_jb" text="开始采集（音量+停止）"/>
        <button id="export" text="导出到题库"/>
        <button id="get_file" text="选择题库文件"/>
        <button id="import" text="导入到题库"/>
        <button id="clear" text="清空题库"/>
        <button id="show" text="查看题库数量"/>
        <text id="tk_file" textSize="12sp" textColor="black" text="题库文件"/>
        <text id="msg" textSize="12sp" textColor="black" text=""/>
    </vertical>
);

// 指定确定按钮点击时要执行的动作
ui.do_jb.click(function(){
    var path = 'run.js'
    execution = engines.execScriptFile(path);
});

function pathToArray(dir) {
    current_dir_array = new Array();
    current_dir_array = ["返回上级目录"];
    files.listDir(dir.join("")).forEach((i) => {
        if (files.isDir(dir.join("") + i)) {
            current_dir_array.push(i + "/");
        } else if (files.isFile(dir.join("") + i)) {
            current_dir_array.push(i);
        }
    });
    return current_dir_array;
}

ui.get_file.click(() => {
    var current_dir_array, dir = ["/", "sdcard", "/"]; //存储当前目录
    function file_select(select_index) {
        switch (select_index) {
            case undefined:
                break;
            case -1:
                return;
            case 0:
                if (dir.length > 3) {
                    dir.pop();
                }
                break;
            default:
                if (files.isFile(files.join(dir.join(""), current_dir_array[select_index]))) {
                    let file_name = (files.join(dir.join(""), current_dir_array[select_index]))
                    toast(file_name)
                    ui.tk_file.setText(file_name);
                    return;

                } else if (files.isDir(files.join(dir.join(""), current_dir_array[select_index]))) {
                    dir.push(current_dir_array[select_index])
                }
        };
        current_dir_array = pathToArray(dir)
        dialogs.select("文件选择", current_dir_array).then(n => {
            file_select(n)
        });
    };
    file_select();
});

ui.export.click(function(){
    files.append('/sdcard/tk.json', JSON.stringify(tk));
    alert('导出完成,文件为:/sdcard/tk.json')
});

ui.clear.click(function(){
    tk = {}
    storage.put('tk', tk)
    alert('清空成功')
});

ui.show.click(function(){
    ui.msg.setText("当前题库数量:" + Object.keys(tk).length);
});


ui.import.click(function(){
    tk_file =  ui.tk_file.text();
    if(files.exists(tk_file)){
        new_tk = JSON.parse(files.read(tk_file))
        for (var key in new_tk) {
            if (!tk.hasOwnProperty(key)) {
                tk[key] = new_tk[key]
            }
        }
        storage.put('tk', tk)
        alert('导入成功')
    }else{
        alert('没有找到文件:' + tk_file)
    }
    
    
});

